import { AcGameObject } from './AcGameObject'
import { Snake } from './Snake'

export class GameMap extends AcGameObject {
  constructor (ctx, parent, store) {
    super()

    this.parent = parent
    this.ctx = ctx
    this.store = store
    this.L = 0
    this.snake = new Snake(ctx, this)
    this.directions = [] // 缓存方向，用户可能快速点了好几个方向，要依次缓存，后面依次执行

    this.status = 'waiting' // waiting => playing => win / lose
  }

  update () {
    this.update_size()
    this.render()
  }

  update_size () {
    this.L = Math.min(this.parent.clientWidth / 17, this.parent.clientHeight / 15)
    // console.log(333, this.ctx.canvas)
    this.ctx.canvas.width = this.L * 17
    this.ctx.canvas.height = this.L * 15
  }

  render() {
    const color_even = '#AAD751', color_odd = '#A2D149'

    for(let i = 0; i < 17; i++) {
      for(let j = 0; j < 15; j++) {
        if((i + j) % 2 === 0) {
          this.ctx.fillStyle = color_even 
        } else {
          this.ctx.fillStyle = color_odd 
        }
        this.ctx.fillRect(i * this.L, j * this.L, this.L, this.L);
      }
    }
  }

  start () {
    // this.ctx.canvas.parent.focus() // canvas 聚焦才能去监听键盘
    
    window.addEventListener('keydown', e => {
      if(e.key === 'w' || e.key === 'ArrowUp') {
        e.preventDefault(); // 不要放在最外层，因为会阻止其他键的行为，如f5刷新
        this.directions.push(0)
      }
      if(e.key === 'd' || e.key === 'ArrowRight') {
        e.preventDefault();
        this.directions.push(1)

      }
      if(e.key === 's' || e.key === 'ArrowDown') {
        e.preventDefault();
        this.directions.push(2)
      }
      // console.log('---left')
      if(e.key === 'a' || e.key === 'ArrowLeft') {
        // console.log('left')
        e.preventDefault();
        this.directions.push(3)
      }
      const k = this.directions.length
      if(k > 1 && this.directions[k - 1] === this.directions[k - 2]) {
        this.directions.pop()
      }
      // 用户可能一次点了超多次，要控制缓存的方向
      while(k > 2) {
        this.directions.splice(0, 1)
        // this.directions.shift()
      }

      // 刚开始时waiting状态不让用户按反方向键
      if(this.status === 'waiting' && k && this.directions[0] !== 3) {
        this.status = 'playing'
        this.snake.direction = this.directions[0]
        this.directions.splice(0, 1)
      }

    })
  }

  win() {
    this.snake.color = 'white'
    this.status = 'win'
    this.store.commit('updateRestart', true)
  }

  lose() {
    this.snake.color = '#fff'
    this.status = 'lose'
    this.store.commit('updateRestart', true)
  }

  restart() {
    this.store.state.score = 0
    this.status = 'waiting'
    this.snake.destroy()
    this.snake = new Snake(this.ctx, this)

    this.store.commit('updateRestart', false)
  }
}
